import React, { FC, useState } from 'react'
import styles from './common.module.scss'
import {
  Typography,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  message,
  Empty,
  Spin,
} from 'antd'
import ListSearch from '@/components/ListSearch'
import useLoadQuestionListData from '@/hooks/useLoadQuestionListData'
import { itemUpDateAPI } from '@/server/question'
import { useRequest } from 'ahooks'
import ListPagination from '@/components/ListPagination'
const { Title } = Typography
const { confirm } = Modal
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
  },
  {
    title: '是否发布',
    dataIndex: 'isPublished',
    render: (isPublished: boolean) => {
      return isPublished ? (
        <Tag color="processing" style={{ color: 'green' }}>
          已发布
        </Tag>
      ) : (
        <Tag>未发布</Tag>
      )
    },
  },
  {
    title: '答卷',
    dataIndex: 'answerCount',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
  },
]
const Trash: FC = () => {
  const { data, loading } = useLoadQuestionListData({ isDeleted: true })
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([])
  const { run } = useRequest(
    async () => {
      // 遍历数据每一项，依次调用异步接口
      for await (const id of selectedRowKeys) {
        await itemUpDateAPI(id)
      }
    },
    {
      manual: true,
      onSuccess: () => {
        message.success('恢复成功！')
      },
      debounceWait: 500, // 防抖
    }
  )
  const TableElemt = !loading ? (
    <Table
      rowSelection={{
        type: 'checkbox',
        onChange: selectedRowKeys => {
          setSelectedRowKeys(selectedRowKeys as string[])
        },
      }}
      dataSource={data.list}
      columns={columns}
      pagination={false}
      rowKey="_id"
    />
  ) : (
    ''
  )
  const del = () => {
    confirm({
      title: '确定删除该问卷吗？',
      content: '删除后将无法恢复',
      onOk: () => {
        message.success('删除成功！')
      },
    })
  }
  const upDate = () => {
    run()
  }
  return (
    <div className={styles['List']}>
      <Title level={3} className={styles['List-header']}>
        <div className={styles.left}>回收站</div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </Title>
      <div className={styles['List-content']}>
        <Space style={{ marginBottom: '10px' }}>
          <Button
            type="primary"
            onClick={upDate}
            disabled={selectedRowKeys.length === 0}>
            恢复
          </Button>
          <Button danger disabled={selectedRowKeys.length === 0} onClick={del}>
            彻底删除
          </Button>
        </Space>
        {!loading ? (
          data.list.length === 0 ? (
            <Empty description="暂无数据" />
          ) : (
            TableElemt
          )
        ) : (
          <div style={{ textAlign: 'center' }}>
            <Spin />
          </div>
        )}
      </div>
      {!loading && <ListPagination total={data.total} />}
    </div>
  )
}

export default Trash
